package org.game.module.dungeonbo;

import java.util.Date;
import java.util.Map;

import org.base.BaseGoods;
import org.cache.GoodsCfgCache;
import org.cfg.DungeonLevelCfg;
import org.cfg.cache.DungeonLevelCfgCache;
import org.error.GameErrorCode;
import org.game.constant.DungeonTypeConstant;
import org.game.constant.SessionConstent;
import org.game.db.bean.DungeonLevel;
import org.game.db.bean.Player;
import org.game.db.cache.DungeonLevelCache;
import org.game.manager.DungeonManager;
import org.game.manager.ItemPackageHelper;
import org.game.manager.PlayerManager;
import org.game.module.fight.AbstractFight;
import org.game.module.fight.FightManager;
import org.game.module.fight.LocalFight;
import org.game.module.fight.handler.ActivityDungeonHandler;
import org.game.module.fight.handler.FightHandler;
import org.game.module.fight.handler.GeneralDungeonHandler;
import org.game.module.fight.handler.MainDungeonHandler;
import org.game.msgBuilder.DungeonMsgBuilder;
import org.game.protobuf.c2s.C2SDungeonMsg;
import org.game.protobuf.s2c.S2CDungeonMsg;
import org.game.protobuf.s2c.S2CHeroMsg.HeroInfo;
import org.game.util.ProtoUnit;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.sojoys.artifact.exception.AbstractLogicModelException;
import com.sojoys.artifact.factory.session.ISession;
import com.sojoys.artifact.tools.ToolError;

@SuppressWarnings({"unchecked"})
public class DungeonBOImpl implements DungeonBO {

    @Override
    public byte[] fightStart(ISession session, C2SDungeonMsg.FightStartMsg msg) throws AbstractLogicModelException {
        int cid = msg.getLevelCid();
        DungeonLevelCfg dungeonLevelCfg = DungeonLevelCfgCache.me().getById(cid);
        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, dungeonLevelCfg == null);
        Player player = session.getAttr(SessionConstent.PLAYER);
        

        //获取关卡记录
        DungeonLevel dungeonLevel = DungeonLevelCache.me().getDungeonLevelCacheProxy().getByPlayerIdCid(player.getId(), cid);
        if (dungeonLevel == null) {
            dungeonLevel = new DungeonLevel(0L, player.getId(), cid, 0, 0, false,Lists.newArrayList(),new Date(),0);
            dungeonLevel.insert();
        }
        
        // 创建战斗处理器
        FightHandler handler = null;
        switch (dungeonLevelCfg.getDungeonType()) {
		case DungeonTypeConstant.DUNGEON_TYPE_MAIN_LINE:
			handler = new MainDungeonHandler(player, dungeonLevelCfg, dungeonLevel,dungeonLevelCfg.getDungeonLevelGroupCfg());
			break;
		case DungeonTypeConstant.DUNGEON_TYPE_GENERAL:
			handler = new GeneralDungeonHandler(player, dungeonLevelCfg, dungeonLevel,dungeonLevelCfg.getDungeonLevelGroupCfg());
			break;
		case DungeonTypeConstant.DUNGEON_TYPE_ACTIVITY:
			handler = new ActivityDungeonHandler(player, dungeonLevelCfg, dungeonLevel, dungeonLevelCfg.getDungeonLevelGroupCfg());
			break;
		}
        
        // 预先获得战斗奖励
        Map<Integer, Integer> rewards = Maps.newHashMap();
        
        int rewardId = 0;
        if (dungeonLevelCfg.getFirstReward() != 0 && dungeonLevel.getTotalFightCount() == 0){
        	rewardId = dungeonLevelCfg.getFirstReward();
        }else{
        	rewardId = dungeonLevelCfg.getReward();
        }
        if (rewardId != 0) {
        	BaseGoods cfg = GoodsCfgCache.me().get(rewardId);
        	ItemPackageHelper.unpack(cfg.getUseProfit(), null, rewards);
		}
        
        // 查找助战英雄
        HeroInfo helpHero = null;
        int helpPlayerId = msg.getHelpPlayerId();
        int helpHeroCid = msg.getHelpHeroCid();
        if (helpPlayerId != 0){
            ToolError.isAndTrue(GameErrorCode.HELP_FIGHTER_IS_NOT_COLD_DOWN,"助战玩家还未冷却",FightManager.isHelpFightColdDown(player,helpPlayerId,new Date()));
        	helpHero = PlayerManager.me().getRemoteHeroInfo(helpPlayerId, helpHeroCid);
        }
        
        // 构建 & 开始战斗
        AbstractFight fight = LocalFight.newBuilder().setHandler(handler).setHelpHero(helpHero).setRewards(rewards).setHelpPid(helpPlayerId).build();
        fight.start();
        player.getPlayerProxy().setCurrentFightId(fight.getFightId());
        return null;
    }

    @Override
    public byte[] fightOver(ISession session, C2SDungeonMsg.FightOverMsg msg) throws AbstractLogicModelException {

//        int cid = msg.getLevelCid();
//        boolean isWin = msg.getIsWin();
//        int maxBatter = msg.getBatter();	//最大连击数
//        int pickUpTypeCount = msg.getPickUpTypeCount();//拾取道具种类个数
//    	int pickUpCount = msg.getPickUpCount();//拾取道具个数
//        List<Integer> goalsList = msg.getGoalsList();
        Player player = session.getAttr(SessionConstent.PLAYER);
//        DungeonLevelCfg dungeonLevelCfg = DungeonLevelCfgCache.me().getById(cid);
//
//        //校验提交的关卡cid是否是服务器记录的关卡cid，并清除记录的关卡cid
//        int currentDungeonCid = player.getPlayerProxy().getCurrentDungeonCid();
//        player.getPlayerProxy().setCurrentDungeonCid(0);
//        ToolError.isAndTrue(GameErrorCode.CLIENT_PARAM_IS_ERR, cid != currentDungeonCid);
//        List<Integer> goals = msg.getGoalsList();
    	String fightId = player.getPlayerProxy().getCurrentFightId();
    	AbstractFight fight = FightManager.me().getById(fightId);
		fight.setAttr("submit", msg).over(msg.getIsWin());
    	return null;
    }

    @Override
    public byte[] promoteStory(ISession session, C2SDungeonMsg.ProgressMsg msg) throws AbstractLogicModelException {

        int cid = msg.getMainLineCid();
        Player player = session.getAttr(SessionConstent.PLAYER);

        return DungeonManager.promoteStory(player, DungeonTypeConstant.DUNGEON_TYPE_MAIN_LINE, cid);
    }

    @Override
    public byte[] getDungeonInfo(ISession session, C2SDungeonMsg.GetLevelInfo msg) throws AbstractLogicModelException {

        Player player = session.getAttr(SessionConstent.PLAYER);
        S2CDungeonMsg.GetLevelInfo dungeonRecordMsg = DungeonMsgBuilder.getDungeonRecordMsg(player);

        return ProtoUnit.toByte(dungeonRecordMsg);
    }

    @Override
    public byte[] buyFightCount(ISession session, S2CDungeonMsg.BuyFightCount msg) throws AbstractLogicModelException {
        Player player = session.getAttr(SessionConstent.PLAYER);
        int cid = msg.getCid();
        return DungeonManager.buyFightCount(player, cid);
    }

    @Override
    public byte[] getLevelGroupReward(ISession session, C2SDungeonMsg.GetLevelGroupReward msg) throws AbstractLogicModelException {
        Player player = session.getAttr(SessionConstent.PLAYER);
        int levelGroupCid = msg.getCid();
        int difficulty = msg.getDifficulty();
        int starNum = msg.getStarNum();
        return DungeonManager.getLevelGroupReward(player, levelGroupCid,difficulty, starNum);
    }
}
